package com.example.seabedmusic.presenter;

import android.content.Context;
import android.util.Log;

import com.example.seabedmusic.entity.HotSong;
import com.example.seabedmusic.views.HotMusicActivity;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class HotMusicPresenter {

    public interface IHotMusicView {
        void showHotSongs(List<HotSong> songs);
        void showToast(String msg);
        void showLoading();
        void hideLoading();
        void appendHotSongs(List<HotSong> songs);
        void updateRankInfo(JSONObject rankInfo); // 新增方法
    }

    private IHotMusicView mView;
    private Context mContext;
    private OkHttpClient mClient;
    private List<HotSong> allSongs = new ArrayList<>(); // 存储所有歌曲
    private int currentPage = 1;
    private static final int PAGE_SIZE = 30; // 每页数量
    private boolean isLoading = false;

    public HotMusicPresenter(IHotMusicView view, Context context) {
        mView = view;
        mContext = context;

        mClient = new OkHttpClient.Builder()
                .connectTimeout(15, TimeUnit.SECONDS)
                .readTimeout(15, TimeUnit.SECONDS)
                .writeTimeout(15, TimeUnit.SECONDS)
                .build();
    }

    public void getHot() {
        if (isLoading) return;

        mView.showLoading();
        currentPage = 1;
        allSongs.clear();
        performHotRequest(currentPage);
    }

    // 加载更多数据
    public void loadMore() {
        if (isLoading) return;

        currentPage++;
        performHotRequest(currentPage);
    }

    private void performHotRequest(int page) {
        isLoading = true;

        // 使用分页参数
        String url = "https://m.kugou.com/rank/info/?rankid=8888&page=" + page + "&json=true&pagesize=" + PAGE_SIZE;

        Log.d("HotMusic", "请求第 " + page + " 页数据: " + url);

        Request request = new Request.Builder()
                .url(url)
                .addHeader("User-Agent", "Mozilla/5.0 (Linux; Android 10; SM-G975F) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Mobile Safari/537.36")
                .addHeader("Accept", "application/json, text/plain, */*")
                .addHeader("Referer", "https://m.kugou.com/rank.html")
                .build();

        mClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("HotMusic", "第 " + page + " 页网络请求失败: " + e.getMessage());
                runOnUiThread(() -> {
                    isLoading = false;
                    if (page == 1) {
                        mView.hideLoading();
                        mView.showToast("网络连接失败");
                    } else {
                        mView.showToast("加载更多失败");
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.d("HotMusic", "第 " + page + " 页响应状态码: " + response.code());

                if (!response.isSuccessful()) {
                    Log.e("HotMusic", "第 " + page + " 页服务器响应异常: " + response.code());
                    runOnUiThread(() -> {
                        isLoading = false;
                        if (page == 1) {
                            mView.hideLoading();
                            mView.showToast("服务器响应异常: " + response.code());
                        } else {
                            mView.showToast("加载更多失败");
                        }
                    });
                    return;
                }

                try {
                    String responseBody = response.body().string();
                    Log.d("HotMusic", "第 " + page + " 页响应数据长度: " + responseBody.length());

                    List<HotSong> pageSongs = parseKugouResponse(responseBody, page);

                    runOnUiThread(() -> {
                        isLoading = false;

                        if (page == 1) {
                            // 第一页数据
                            allSongs.clear();
                            allSongs.addAll(pageSongs);
                            mView.showHotSongs(allSongs);
                            mView.hideLoading();

                            // 如果还有更多数据，继续加载
                            if (pageSongs.size() == PAGE_SIZE && allSongs.size() < 500) {
                                loadMore();
                            }
                        } else {
                            // 后续页数据
                            int startSize = allSongs.size();
                            allSongs.addAll(pageSongs);
                            mView.appendHotSongs(pageSongs);

                            // 继续加载直到达到500首或没有更多数据
                            if (pageSongs.size() == PAGE_SIZE && allSongs.size() < 500) {
                                loadMore();
                            }
                        }
                    });

                } catch (Exception e) {
                    Log.e("HotMusic", "第 " + page + " 页处理响应数据失败: " + e.getMessage());
                    runOnUiThread(() -> {
                        isLoading = false;
                        if (page == 1) {
                            mView.hideLoading();
                            mView.showToast("数据处理失败");
                        } else {
                            mView.showToast("加载更多失败");
                        }
                    });
                }
            }
        });
    }

    /**
     * 解析酷狗API响应 - 加载更多歌曲
     */
    private List<HotSong> parseKugouResponse(String jsonData, int page) {
        List<HotSong> songs = new ArrayList<>();

        try {
            JSONObject jsonObject = new JSONObject(jsonData);

            // 解析排行榜信息（只在第一页时解析）
            if (page == 1) {
                parseRankInfo(jsonObject);
            }

            if (jsonObject.has("songs")) {
                JSONObject songsObj = jsonObject.getJSONObject("songs");

                int totalSongs = songsObj.optInt("total", 0);
                Log.d("HotMusic", "第 " + page + " 页总歌曲数: " + totalSongs);

                if (songsObj.has("list")) {
                    JSONArray songsArray = songsObj.getJSONArray("list");
                    Log.d("HotMusic", "第 " + page + " 页找到歌曲列表，长度: " + songsArray.length());

                    // 计算正确的排名（考虑分页）
                    int startRank = (page - 1) * PAGE_SIZE + 1;

                    for (int i = 0; i < songsArray.length(); i++) {
                        JSONObject songJson = songsArray.getJSONObject(i);
                        HotSong song = parseSongInfo(songJson, startRank + i);
                        if (song != null) {
                            songs.add(song);
                        }
                    }
                }
            }

        } catch (JSONException e) {
            Log.e("HotMusic", "第 " + page + " 页JSON解析异常: " + e.getMessage());
        }

        Log.d("HotMusic", "第 " + page + " 页解析完成，共 " + songs.size() + " 首歌曲");
        return songs;
    }

    /**
     * 解析排行榜信息
     */
    private void parseRankInfo(JSONObject jsonObject) {
        try {
            JSONObject rankInfo = new JSONObject();

            // 排行榜基本信息
            if (jsonObject.has("info")) {
                JSONObject info = jsonObject.getJSONObject("info");

                // 2. 更新时间 - 从API获取
                String updateTime = info.optString("rank_id_publish_date", "");

                // 处理更新时间格式
                if (!updateTime.isEmpty()) {
                    try {
                        // 格式: "2025-11-04 08:30:01" -> "11月4日"
                        String[] dateTimeParts = updateTime.split(" ");
                        if (dateTimeParts.length > 0) {
                            String datePart = dateTimeParts[0];
                            String[] dateParts = datePart.split("-");
                            if (dateParts.length >= 3) {
                                int month = Integer.parseInt(dateParts[1]);
                                int day = Integer.parseInt(dateParts[2]);
                                updateTime = month + "月" + day + "日";
                            }
                        }
                    } catch (Exception e) {
                        Log.w("HotMusic", "时间格式转换失败，使用原始时间: " + updateTime);
                        updateTime = "11月4日"; // 默认值
                    }
                } else {
                    updateTime = "11月4日"; // 默认值
                }

                // 3. 播放次数 - 从API获取
                int totalPlayCount = info.optInt("play_times", 0000);
                String playCount = formatCount(totalPlayCount);

                // 只存储API获取的数据
                rankInfo.put("updateTime", updateTime);
                rankInfo.put("playCount", playCount);

                Log.d("HotMusic", "更新时间: " + updateTime +
                        ", 播放: " + playCount + " (原始: " + totalPlayCount + ")");
            }

            // 通知UI更新排行榜信息
            runOnUiThread(() -> {
                mView.updateRankInfo(rankInfo);
            });

        } catch (Exception e) {
            Log.e("HotMusic", "解析排行榜信息失败: " + e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 格式化数量显示（转换为万为单位）
     */
    private String formatCount(int count) {
        if (count >= 10000) {
            return String.format("%.1f万", count / 10000.0);
        } else {
            return String.valueOf(count);
        }
    }

    /**
     * 解析单首歌曲信息
     */
    private HotSong parseSongInfo(JSONObject songJson, int rank) {
        try {
            HotSong song = new HotSong();

            // 歌曲名
            String songName = songJson.optString("songname", "");
            song.setName(songName.isEmpty() ? "未知歌曲" : songName);

            // 歌手名
            String author = "未知歌手";
            if (songJson.has("authors")) {
                JSONArray authors = songJson.getJSONArray("authors");
                if (authors.length() > 0) {
                    JSONObject firstAuthor = authors.getJSONObject(0);
                    author = firstAuthor.optString("author_name", "未知歌手");
                }
            }
            song.setAuthor(author);

            // 封面URL - 尝试多种来源
            String coverUrl = extractCoverUrl(songJson);
            song.setCover(coverUrl);

            // 专辑名
            song.setAlbum(songJson.optString("album_name", "热门专辑"));

            // 关键：获取歌曲hash，用于播放
            String hash = songJson.optString("hash", "");
            song.setHash(hash);

            // 获取320k音质的hash（如果存在）
            String hash320 = songJson.optString("320hash", "");
            if (!hash320.isEmpty()) {
                song.setHash(hash320); // 优先使用高品质hash
            }

            // 获取SQ无损音质的hash（如果存在）
            String sqHash = songJson.optString("sqhash", "");

            // 调试信息
            Log.d("HotMusic", "歌曲[" + rank + "]: " + song.getName() +
                    " - Hash: " + hash +
                    " - 320Hash: " + hash320 +
                    " - SQHash: " + sqHash);

            song.setRank(rank);
            return song;

        } catch (Exception e) {
            Log.e("HotMusic", "解析单首歌曲失败: " + e.getMessage());
            return null;
        }
    }

    /**
     * 提取封面URL，尝试多种字段
     */
    private String extractCoverUrl(JSONObject songJson) {
        String coverUrl = "";

        try {
            // 1. 尝试从 authors 中获取
            if (songJson.has("authors")) {
                JSONArray authors = songJson.getJSONArray("authors");
                if (authors.length() > 0) {
                    JSONObject firstAuthor = authors.getJSONObject(0);
                    coverUrl = firstAuthor.optString("sizable_avatar", "");
                    if (!coverUrl.isEmpty()) {
                        coverUrl = coverUrl.replace("{size}", "300");
                        Log.d("HotMusic", "从authors获取封面: " + coverUrl);
                    }
                }
            }

            // 2. 尝试从 img 字段获取
            if (coverUrl.isEmpty() && songJson.has("img")) {
                coverUrl = songJson.optString("img", "");
                Log.d("HotMusic", "从img获取封面: " + coverUrl);
            }

            // 3. 尝试从 album_img 字段获取
            if (coverUrl.isEmpty() && songJson.has("album_img")) {
                coverUrl = songJson.optString("album_img", "");
                Log.d("HotMusic", "从album_img获取封面: " + coverUrl);
            }

            // 4. 确保URL格式正确
            if (!coverUrl.isEmpty()) {
                // 移除可能的多余字符
                coverUrl = coverUrl.trim();

                // 将HTTP转换为HTTPS
                if (coverUrl.startsWith("http://")) {
                    coverUrl = coverUrl.replace("http://", "https://");
                    Log.d("HotMusic", "将HTTP转换为HTTPS: " + coverUrl);
                }

                // 添加协议头如果缺失
                if (!coverUrl.startsWith("http")) {
                    if (coverUrl.startsWith("//")) {
                        coverUrl = "https:" + coverUrl;
                    } else {
                        coverUrl = "https://" + coverUrl;
                    }
                    Log.d("HotMusic", "添加HTTPS协议头: " + coverUrl);
                }

                // 确保是有效的图片URL
                if (!coverUrl.contains(".jpg") && !coverUrl.contains(".png") && !coverUrl.contains(".jpeg")) {
                    Log.w("HotMusic", "封面URL可能不是图片格式: " + coverUrl);
                }
            } else {
                // 使用默认封面
                coverUrl = "https://p1.music.126.net/qTSIZ27qiFvRoKj-P30BiA==/109951165895951289.jpg";
                Log.d("HotMusic", "使用默认封面URL");
            }

        } catch (Exception e) {
            Log.e("HotMusic", "提取封面URL失败: " + e.getMessage());
            coverUrl = "https://p1.music.126.net/qTSIZ27qiFvRoKj-P30BiA==/109951165895951289.jpg";
        }

        return coverUrl;
    }

    /**
     * 在UI线程执行
     */
    private void runOnUiThread(Runnable action) {
        if (mContext instanceof android.app.Activity) {
            ((android.app.Activity) mContext).runOnUiThread(action);
        }
    }
}